<template>
  <div class="common-list-container__v2 task-manage-list-container column">
    <!-- start 头部搜索栏 -->
    <div class="header-container">
      <div class="common-list-header__v2">
        <div class="flex-x base-search-group input-with-append-search">
          <el-input v-model.trim="searchParams.likeSearch" :placeholder="$t('common.placeholder.searchTaskManage')"
            prefix-icon="el-icon-search" @keyup.enter.native="handleSearch">
            <el-button type="primary" slot="append" @click="handleSearch">{{ $t('common.base.search') }}</el-button>
          </el-input>
          <el-button class="ml_12" type="plain-third" @click="handleReset">{{ $t('common.base.reset') }}</el-button>

          <advanced-search 
            :fields="advanceSearchColumns" 
            :has-create="false" 
            :has-save="false"
            :search-model="viewportSearchModel" 
            :in-common-use="inCommonUse"
            @changeCommonUse="changeCommonUse($event, advancedSearchCommonUseStorageKey)"
            @search="handleAdvancedSearch" />
        </div>
      </div>

      <div class="base-filter-tag-list-container" v-show="packUp">
        <template>
          <BaseFilterTagList 
            :label="$t('projectManage.taskManageList.taskStatus') + ':'" 
            :active="searchParams.taskStatus"
            :list="dataStatusList" 
            @choose="handleFilterClick($event, 'taskStatus')"
            >
            <template v-slot="{ label, number, value }">
              {{ label }} ({{ number }})
            </template>
          </BaseFilterTagList>
        </template>

        <BaseFilterTagList 
          :label="$t('common.base.createAngle') + ':'" 
          :active="searchParams.searchType"
          :list="createViewList" 
          @choose="handleFilterClick($event, 'searchType')"
          ></BaseFilterTagList>
      </div>
    </div>
    <!-- end 头部搜索栏 -->

    <div class="bbx-normal-pack-up">
      <div @click="packUp = !packUp">
        <i :class="['iconfont', packUp ? 'icon-Icon_up' : 'icon-more']"></i>
      </div>
    </div>

    <div class="task-manage-list-container-content">
      <task-manage-table 
        ref="taskManageRef" 
        :columns="columns" 
        :params="searchParams" 
        :statusList="dataStatusList"
        @handleSelectColumn="handleSelectColumn"
      ></task-manage-table>
    </div>

    <!-- start 选择列 -->
    <biz-select-column ref="bizSelectColumnComponent" @save="saveSelectColumns($event, selectColumnStorageKey)" />
    <!-- end 选择列 -->
  </div>
</template>

<script>
/* components */
import AdvancedSearch from '@src/component/AdvancedSearch/index.vue';
import TaskManageTableList from '@src/modules/projectManage/taskManageList/components/TaskManageTableList.vue';
/* model */
import { ViewTypeComponentNameEnum, createViewList } from '@src/modules/projectManage/taskManageList/model';
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum';
/* util */
import { getColumnFields } from '@src/modules/projectManage/projectManageList/util';
import { t } from '@src/locales';
import _ from 'lodash';
/* hooks */
import { useSelectColumn } from '@src/modules/projectManage/projectManageList/hooks/useSelectColumn';
import { useAdvancedSearch } from '@src/modules/projectManage/projectManageList/hooks/useAdvancedSearch';
import { useFetchTaskManageFieldList, useFetchTaskManageStatusList } from '@src/modules/projectManage/taskManageList/hooks/useFetch';
/* vue */
import { ref, onMounted, reactive, computed } from 'vue';

export default {
  name: 'task-manage-list-page',
  components: {
    AdvancedSearch,
    [TaskManageTableList.name]: TaskManageTableList,
  },
  setup(props, { }) {
    // 选择列
    const { columns, buildSelectColumns, saveSelectColumns } = useSelectColumn();
    // 高级搜索列
    const { viewportSearchModel, inCommonUse, advanceSearchColumns, buildAdvancedColumns, changeCommonUse, recoverCommonUse } = useAdvancedSearch();

    // 任务管理数据
    const { fields, fetchTaskManageFieldList } = useFetchTaskManageFieldList();
    const { dataStatusList, fetchTaskManageStatusList } = useFetchTaskManageStatusList();

    // 选择列ref
    const bizSelectColumnComponent = ref(null);
    // 当前视图组件ref
    const taskManageRef = ref(null);
    // 收起折叠
    let packUp = ref(true);

    // 当前视图
    let currentView = ref(ViewTypeComponentNameEnum.Table);
    // 选择列缓存key
    const selectColumnStorageKey = computed(() => `${currentView.value}_${searchParams.templateId}_select_column`);
    // 高级搜索常用字段
    const advancedSearchCommonUseStorageKey = ref(StorageKeyEnum.TaskManageListAdvancedSearchCommonUseFields);

    // 构建搜索参数
    const buildParams = () => {
      return {
        likeSearch: '',
        templateId: '',
        searchType: 'ALL',
        taskStatus: '',
        conditions: [],
        systemConditions: [],
      }
    }

    // 搜索参数
    let searchParams = reactive(buildParams());

    // 构建选择列
    const buildColumns = () => {
      const originFields = getColumnFields(fields.value, currentView.value);
      buildSelectColumns(originFields, selectColumnStorageKey.value);
    }

    // 选择列
    const handleSelectColumn = () => {
      bizSelectColumnComponent.value?.open(columns.value);
    };

    // 视图筛选搜索
    const handleFilterClick = ({ value }, key) => {
      searchParams[key] = value;

      // 切换视角 - 更新状态
      if (key == 'searchType') {
        fetchTaskManageStatusList(searchParams);
      }
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      taskManageRef.value?.search(true);
    }

    // 重置搜索
    const handleReset = () => {
      Object.assign(searchParams, buildParams());

      // 重置高级搜索：会触发高级搜索事件handleAdvancedSearch
      viewportSearchModel.value = [];
    }

    // 高级搜索
    const handleAdvancedSearch = (searchModel) => {
      // TODO 暂时处理
      const timeData = ['planStartTime', 'planEndTime', 'createTime', 'completeTime'];
      const { conditions = [], systemConditions = [] } = searchModel;

      systemConditions.forEach(x => {
        if(x.property === 'projectId') x.value = x.value?.value || '';
        if(timeData.includes(x.property)) {
          x.betweenValue1 = new Date(x.betweenValue1).getTime();
          x.betweenValue2 = new Date(x.betweenValue2).getTime();
        }
      })

      searchParams.conditions = conditions;
      searchParams.systemConditions = systemConditions;

      handleSearch();
    }

    // 修改搜索列的key
    const setFieldName = (fields = []) => {
      const obj = {
        'missionNo': 'taskNumber',
        'missionName': 'taskName',
        'managerPerson': 'manager',
        'missionContent': 'taskDesc',
        'projectName': 'projectId',
        'createUser': 'createUid',
        'expectTime': 'expectWorkTime',
      }

      return fields.map(x => { 
        x.fieldName = obj[x?.fieldName] || x?.fieldName;
        if(x.fieldName === 'projectId') x.displayName = i18n.t('common.projectManage.affiliationProject');

        return x;
      })
    }

    // 初始化项目类型字段
    const initializeTaskManageTypeFields = async () => {
      // 获取项目类型字段
      await fetchTaskManageFieldList(searchParams.templateId);
      // 构建选择列数据
      buildColumns();
      // 构建高级搜索列
      buildAdvancedColumns(setFieldName(fields.value));
    }

    onMounted(() => {
      // 恢复常用
      recoverCommonUse(advancedSearchCommonUseStorageKey.value);
      // 获取项目状态
      fetchTaskManageStatusList(searchParams);
      // 初始化项目字段
      initializeTaskManageTypeFields();
    });

    return {
      packUp,
      createViewList,
      dataStatusList,
      currentView,
      taskManageRef,
      selectColumnStorageKey,
      advancedSearchCommonUseStorageKey,

      fields,
      columns,
      searchParams,

      inCommonUse,
      viewportSearchModel,
      advanceSearchColumns,
      bizSelectColumnComponent,

      handleSearch,
      handleReset,
      handleFilterClick,

      changeCommonUse,
      handleAdvancedSearch,

      saveSelectColumns,
      handleSelectColumn,
    };
  },
};
</script>

<style lang="scss" scoped>
@import "@src/assets/scss/common-list.scss";

.task-manage-list-container {

  .common-list-header__v2 {
    border-radius: 4px 4px 0 0 !important;

    .el-dropdown-link {
      color: $text-color-primary;
      cursor: pointer;
    }

    .set-field-btn {
      padding-left: 12px;
      margin-left: 12px;
      border-left: 1px solid $color-border-l1;

      .iconfont {
        font-size: $font-size-base;
        color: $text-color-regular;
        cursor: pointer;
      }
    }
  }

  .base-filter-tag-list-container {
    background: #fff;
    border-radius: 0 0 4px 4px;
    padding: 0 16px 16px;

    .base-filter-tag-list__tag {
      .iconfont {
        font-size: $font-size-small;
        color: $text-color-regular;
        margin-left: 4px;
      }
    }

    .custom-status-filter-container {
      margin-bottom: 12px;

      ::v-deep .el-checkbox-group {
        padding-left: 106px;
        display: flex;
        flex-wrap: wrap;

        .el-checkbox {
          max-width: 256px;
          height: 22px;
          padding: 0 12px;
          margin-right: 0;

          color: $text-color-secondary;
          font-size: 0;
          font-weight: normal;

          display: inline-flex;
          align-items: center;

          &__label {
            flex: 1;
            font-size: 13px;
            display: flex;
            overflow: hidden;

            span {
              flex: 1;
              @include text-ellipsis();
            }

            &:hover {
              color: $color-primary;
            }
          }
        }
      }
    }
  }

  &-content {
    flex: 1;
    overflow: hidden;
  }
}
</style>